layui.jquery(function(){

  // MathJax.Hub.Config({
  //     extensions: ["tex2jax.js"],
  //     jax: ["input/TeX","output/HTML-CSS"],
  //     tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
  // });
  // MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
  var $ = layui.jquery;
  var layer = layui.layer;
  var form = layui.form;
  app.initFn = function(){
    app.examList();

    app.bindCreateExam();
    app.bindExamList();
    app.bindCreatePaper();
    app.bindPaperList();
    app.bindQuestionList();
    app.bindCreateQuestion();
  };
  app.showLogin = function(){
    //未登录弹出登录框
    app.layIdx = layer.open({
      type: 1, title: "欢迎登录", closeBtn: false, area: '380px;', shade: 1, id: 'login', btn: ['立即登录'], move: false,
      content: (['<form class="layui-form" action="">',
        '    <div class="layui-form-item">',
        '        <label class="layui-form-label">账号</label>',
        '        <div class="layui-input-inline">',
        '            <input id="account" type="text" name="account" required="" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input">',
        '        </div>',
        '    </div>',
        '    <div class="layui-form-item">',
        '        <label class="layui-form-label">密码</label>',
        '        <div class="layui-input-inline">',
        '            <input id="password" type="password" name="password" required="" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">',
        '        </div>',
        '    </div>',
        '</form>'].join(""))
      ,success: function(layero){
        layero.find('.layui-layer-btn').css('text-align', 'center');
      }
      ,yes:function(){
        app.login();
      }
    });
  };
  app.isLogin = function(rst){
    if(rst && rst.error==1 && (rst.errMsg==undefined || rst.errMsg=="")){
      app.showLogin();
      return false;
    }else if(rst && (rst.constructor.name=="Array" || rst.error==0)){
      return true;
    }else {
      return false;
    }
  };
  app.examList = function(){
    $.ajax({
      url: app.host+'/examList', type: 'get', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
      success: function(rst){
        if(app.isLogin(rst)){
          $("body > .content").show();
          app.examListData = rst;
          app.showExamList();
        }
      }
    });
  };
  app.bindCreateExam = function(){
    $(".backToExamList").click(function(){
      app.showExamList();
    });
    $("#saveExam").click(function(){
      var exam = {
        exam_name: $("#examName").val(),
        // statement: app.encodeHtml(app.ued.getContent())
        statement: app.ued.getContent()
      }, class_type = [];
      $("[name='class_type']:checked").each(function(a,b){
        class_type.push($.trim($(b).val()));
      });
      exam.class_type = class_type.join(",");
      if(exam.name==""){
        layer.msg("请输入考试名称");
      }else {
        if(app.nowExamId){
          exam.id = app.nowExamId;
          exam.token = app.nowExamToken;
          exam.status = app.nowExamStatus;
        }
        $.ajax({
          url: app.host+'/createExam', type: 'post', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
          data: exam,
          success: function(rst) {
            if(app.isLogin(rst)){
              app.examList();
            }else {
              layer.msg(rst.errMsg);
            }
          }
        });
      }
    });
  };
  app.showCreateExam = function(id,name,details,title, e){
    app.nowExamId = id;
    app.nowExamName = name;
    app.title.text(title);
    $("#examName").val(name);
    app.ued.setContent(details);
    $("[name='class_type']:checked").each(function(a,b){
      $(b).prop("checked",false).next().removeClass("layui-form-checked");
    });
    if(e && e.length>0){
      for(var i=0,l=e.length;i<l;i++){
        $("[value='"+e[i]+"']").prop("checked",true).next().addClass("layui-form-checked");
      }
    }
    $("#createExam").show().siblings().hide();
  };
  app.showExamList = function(rst){
    app.title.text('考试列表');
    $("#examList").show().siblings().hide();
    var _h = '';
    for(var i=0, l=app.examListData.length; i<l; i++){
      var d = app.examListData[i];
      _h += '<tr><td>'+d.exam_name+'</td>'+
            '<td data-id="'+d.id+'" data-type="' + d.class_type + '" data-name="'+d.exam_name+'" data-token="' + d.token + '" data-status="'+ d.status + '" data-details='+"'"+
            app.html2Escape(d.statement)+
            // app.escape2Html
            // app.decodeHtml(d.statement)+
            "'"+'><a class="layui-btn showPaperList">查看</a><a class="layui-btn editExam">修改</a></td>'+
            '<td>http://uc.gzxueersi.com/exam/#/?token=' + d.token +
            '</td></tr>';
    }
    $("#examList table tbody").html(_h);
  };

  app.bindExamList = function(){
    $(".toCreateExam").click(function(){
      app.showCreateExam("","","","新增考试",[]);
    });
    $("#examList table").delegate(".editExam", "click" , function(){
      var dom = $(this).parent();
      var name = dom.attr("data-name");
      var details = dom.attr("data-details");
      app.nowExamToken = dom.attr("data-token");
      app.nowExamType = dom.attr("data-type").split(",")
      app.nowExamStatus = dom.attr("data-status")
      app.showCreateExam(dom.attr("data-id"), name, details, '修改考试-' + name, app.nowExamType);
    });
    $("#examList table").delegate(".showPaperList", "click" , function(){
      app.nowExamId = $(this).parent().attr("data-id");
      app.nowExamName = $(this).parent().attr("data-name");
      app.paperList();
    });
    app.ued = UE.getEditor('examDetails',{
      toolbars: [app.tool]
    });
  };
  app.bindCreatePaper = function(){
    $(".backToPaperList").click(function(){
      app.showPaperList();
    });
    $("#addPaperUrl").click(function(){
      var urlDom = $(".paperUrl").last();
      var name = urlDom.find(".urlName").val()
      var url = urlDom.find(".urlAddress").val()
      if(name!="" && url!=""){
        $("#paper_url").append(['<label class="layui-form-label">链接</label><div class="layui-input-inline paperUrl">',
            '<input type="text" class="urlName layui-input" placeholder="请输入链接名称" value="">',
            '<input type="text" class="urlAddress layui-input" placeholder="请输入链接地址" value="">',
            '<a class="deletePaperUrl" href="javascript:;">删除</a>',
          '</div>'].join(""));
      }else {
        layer.msg("请先完善当前链接信息再新增链接")
      }

    });
    $("#paper_url").delegate(".deletePaperUrl", "click" , function(){
      $(this).parent().prev().remove();
      $(this).parent().remove();
    });

    $("#savePaper").click(function(){
      var score = $("#score").val(), statement = $("#paper_statement").val()
          _d = {"subject": $("#subject").val(), "score": score, "exam_id": app.nowExamId, statement: statement,};
      if(app.nowPaperId>0){
        _d.id = app.nowPaperId;
      }
      var urlDom = $(".paperUrl"),urls = [];
      for(var i=0; i<urlDom.length; i++){
        var title = $(urlDom[i]).find(".urlName").val()
        var url = $(urlDom[i]).find(".urlAddress").val()
        if(title && url){
          urls.push({title:title, url:url});
        }
      }
      _d.url = JSON.stringify(urls);
      if(score && score>0){
        $.ajax({
          url: app.host+'/createPaper', type: 'post', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
          data: _d,
          success: function(rst){
            if(app.isLogin(rst)){
              app.paperList();
            }else {
              layer.msg(rst.errMsg);
            }
          }
        });
      }else {
        layer.msg("请输入总分");
      }
    });
  };
  app.paperList = function(){
    $.ajax({
      url: app.host+'/paperList', type: 'get', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
      data: {
        exam_id: app.nowExamId
      },
      success: function(rst){
        if(app.isLogin(rst)){
          app.paperListData = rst;
          app.showPaperList();
        }
      }
    });
  };
  app.title = $(".site-h1");
  app.showCreatePaper = function(a,b,c){
    app.nowPaperId = a;
    app.nowPaperSubject = b;
    app.title.text(c);
    $("#createPaper").show().siblings().hide();
  };
  app.bindPaperList = function(){
    $(".toCreatePaper").click(function(){
      $("#paper_url").html("");
      app.showCreatePaper(0,"",'创建试卷');
    });
    $("#paperList table").delegate(".editPaper", "click" , function(){
      var dom = $(this).parent();
      var subject = dom.attr("data-subject");
      app.showCreatePaper(dom.attr("data-id"), subject, '修改' + subject + '试卷');
      $("#score").val(dom.attr("data-score"));
      $("#paper_statement").val(dom.attr("data-statement"));
      var _t = $("#subject").val(subject).next();
      // console.log(_t.find('input'));
      _t.find('input').val(subject).attr('placeholder',subject);
      _t.find('[lay-value="'+subject+'"]').addClass('layui-this').siblings().removeClass('layui-this');
      $("#paper_url").html("");
      var url = dom.attr("data-url")?JSON.parse(dom.attr("data-url")):[];
      for(var i=0;i<url.length;i++){
        $("#paper_url").append(['<label class="layui-form-label">链接</label><div class="layui-input-inline paperUrl">',
            '<input type="text" class="urlName layui-input" placeholder="请输入链接名称" value="'+url[i].title+'">',
            '<input type="text" class="urlAddress layui-input" placeholder="请输入链接地址" value="'+url[i].url+'">',
            '<a class="deletePaperUrl" href="javascript:;">删除</a>',
          '</div>'].join(""));
      }
    });
    $("#paperList table").delegate(".showQuestionList", "click" , function(){
      app.nowPaperId = $(this).parent().attr("data-id");
      app.nowPaperSubject = $(this).parent().attr("data-subject");
      app.showQuestionList();
    });
    $("#paperList table").delegate(".publishPaper", "click" , function(){
      var _this = this;
      app.layIdx = layer.confirm('确定发布'+($(this).parent().attr("data-subject"))+'试卷?', {icon: 3, title:'提示'}, function(index){
        $.ajax({
          url: app.host+'/confirm', type: 'get', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
          data: {"paper_id": $(_this).parent().attr("data-id"), "exam_id": app.nowExamId},
          success: function(rst){
            if(app.isLogin(rst)){
              layer.msg("发布成功");
              $(_this).remove();
              layer.close(app.layIdx);
            }else{
              layer.msg(rst.errMsg);
            }
          }
        });
      });
    });
    // 代理删除试卷按钮
    // $("#paperList table").delegate(".deletePaper", "click" , function(){
    //   var id = $(this).parent().attr("data-id");
    //   layer.confirm('确定删除'+($(this).parent().attr("data-subject"))+'试卷?', {icon: 3, title:'提示'}, function(index){
    //     // 确定删除该试卷
    //     $.ajax({
    //       url: app.host+'/paperList', type: 'get', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
    //       data: {"name": account, "password": pwd},
    //       success: function(rst){
    //
    //
    //       }
    //     });
    //     layer.close(index);
    //   });
    // });
  };
  app.addIndex = function(arr){
    for(var i=0, l=arr.length;i<l;i++){
      arr[i].index = (i+1);
    }
    return arr;
  };
  // 显示试卷所有题目
  app.showQuestionList = function(){
    var id = app.nowPaperId;
    if(id && id>0){
      app.title.text(app.nowPaperSubject + "-题目列表");
      $("#questionList").show().siblings().hide();
      $.ajax({
        url: app.host+'/createPaper', type: 'get', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
        data: {"paper_id": id},
        success: function(rst){
          if(app.isLogin(rst)){
            app.questionList = app.addIndex(rst);
            var _h = '';
            for(var i=0, l=app.questionList.length; i<l; i++){
              var d = app.questionList[i];
              _h += '<tr><td>'+d.index+'</td><td>'+d.score+'</td><td>'+d.answer_num+'</td>'+
                    '<td data-id="'+d.id+'" data-idx="'+d.index+'"><a class="layui-btn editQuestion">修改</a><a class="layui-btn deleteQuestion">删除</a></td></tr>';
            }
            $("#questionList table tbody").html(_h);
          }else{
            layer.msg("试卷题目列表为空,或获取试卷题目列表出错");
          }
        }
      });
    }

  };
  app.bindQuestionList = function(){
    $("#questionList table").delegate(".editQuestion", "click" , function(){
      app.nowQuestionId = $(this).parent().attr("data-id");
      app.nowQuestionIdx = $(this).parent().attr("data-idx");
      app.showCreateQuestion();
    });
    $("#questionList table").delegate(".deleteQuestion", "click" , function(){
      var _this = this;
      layer.confirm('确定删除问题'+($(this).parent().attr("data-idx")), {icon: 3, title:'提示'}, function(index){
        $.ajax({
          url: app.host+'/getQuestion', type: 'post', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
          data: {"paper_id": app.nowPaperId,"status":0, "id":$(_this).parent().attr("data-id")},
          success: function(rst){
            if(app.isLogin(rst)){
              layer.msg("删除成功");
              app.showQuestionList();
            }else{
              layer.msg(rst.errMsg);
            }
          }
        });
      });
    });


  };
  // 新建或修改题目
  app.showCreateQuestion = function(){
    function initCreateQuestion(a,b,m,c,d,e,f) {
      $("#questionScore").val(a);
      $("#answerNum").val(b);
      $("[name='answer']:checked").each(function(a,b){
        $(b).prop("checked",false).next().removeClass("layui-form-checked");
      });
      if(e && e.length>0){
        for(var i=0,l=e.length;i<l;i++){
          $("[value='"+e[i]+"']").prop("checked",true).next().addClass("layui-form-checked");
        }
      }
      app.uem.setContent(m);
      app.ueq.setContent(c);
      app.uea.setContent(d);
      app.uer.setContent(f);
    }
    initCreateQuestion($("#questionScore").val(),$("#answerNum").val(),"","","","","");
    var w = '新建';
    $("#questionIdx").text(app.nowQuestionIdx);

    if(app.nowQuestionId>0) {
      w = '修改';
      var q = app.questionList[app.nowQuestionIdx-1];
      if(q.answer_num>0){
        initCreateQuestion(q.score,q.answer_num,q.material,q.question,"",q.answer,q.resolution);
      }else {
        initCreateQuestion(q.score,q.answer_num,q.material,q.question,q.answer,"",q.resolution);
      }
    }
    app.title.text(app.nowPaperSubject + "试卷-"+w+"题目");
    $("#createQuestion").show().siblings().hide();
  };
  app.bindCreateQuestion = function(){
    $(".toCreateQuestion").click(function(){
      app.nowQuestionId = 0;
      app.nowQuestionIdx = app.questionList.length+1;;
      app.showCreateQuestion();
    });
    $(".backToQuestionList").click(function(){
      app.showQuestionList();
    });

    app.uem = UE.getEditor('material',{
      toolbars: [app.tool]
    });
    app.ueq = UE.getEditor('questionContent',{
      toolbars: [app.tool]
    });
    app.uea = UE.getEditor('questionAnwser',{
      toolbars: [app.tool]
    });
    app.uer = UE.getEditor('questionResolution',{
      toolbars: [app.tool]
    });
    // app.ueq.ready(function(){
    //   app.ueq.addListener( "selectionchange", function () {
    //     katex.render(app.ueq.getContent(), document.querySelector("#katexPreview"));
    //     // "c = \pm\sqrt{a^2 + b^2}"
    //   });
    // });
    $('#katexContent').bind('input propertychange', function(){
      katex.render($(this).val(), document.querySelector("#katexPreview"),{
        displayMode: true,
        throwOnError: false
      });
    });
    $("#addKatex").click(function(){
      var key = $("[name='katex']:checked").val(),
          str = $("#katexPreview").html();
      if(key==1){
        app.ueq.setContent(app.ueq.getContent() + str);
      }else if(key==2) {
        app.uea.setContent(app.uea.getContent() + str);
      }else if(key==4) {
        app.uer.setContent(app.uer.getContent() + str);
      }else {
        app.uem.setContent(app.uem.getContent() + str);
      }
    });

    $("#preQuestion").click(function(){
      if(app.nowQuestionIdx==1){
        layer.msg("已经是第一题");
      }else{
        app.nowQuestionIdx--;
        app.nowQuestionId = app.questionList[app.nowQuestionIdx-1].id;
        app.showCreateQuestion();
      }
    });
    $("#nextQuestion").click(function(){
      if(app.nowQuestionIdx==app.questionList.length){
        app.layIdx = layer.confirm('已经是最后一题,新建题目?', {icon: 3, title:'提示'}, function(index){
          layer.close(app.layIdx);
          // app.nowQuestionIdx++;
          // app.nowQuestionId = 0;
          // app.showCreateQuestion();
          $(".toCreateQuestion").click();
        });

      }else{
        app.nowQuestionIdx++;
        app.nowQuestionId = app.questionList[app.nowQuestionIdx-1].id;
        app.showCreateQuestion();
      }
    });

    $("#saveQuestion, #saveQuestionPreview").click(function(){
      var preview = $(this).attr("data-preview");
      var question = app.ueq.getContent();
      var answer = app.uea.getContent();
      var resolution = app.uer.getContent();
      var material = app.uem.getContent();
      var answerNum = $("#answerNum").val();
      var score = $("#questionScore").val();
      if(answerNum>0){
        answer = '';
        $("[name='answer']:checked").each(function(a,b){
          answer += $.trim($(b).val());
        });
      }
      var _d = {"paper_id": app.nowPaperId, "material":material, "question": question,
                "answer":answer, "resolution":resolution, "answer_num":answerNum, "score":score, "status":1},
          uri = '/question';
      if(app.nowQuestionId>0){
        _d.id=app.nowQuestionId;
        uri = '/getQuestion';
      }

      $.ajax({
        url: app.host + uri, type: 'post', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
        data: _d,
        success: function(rst){
          if(app.isLogin(rst)){
            if(preview==1){
              window.open(location.origin + location.pathname + "?preview=1&id=" + app.nowQuestionId?app.nowQuestionId:rst.id);
              app.showCreateQuestion();
            }else {
              if(app.nowQuestionId==0){ // 继续新增题目
                layer.msg("新增题目成功");
                app.showCreateQuestion();
                // app.nowQuestionId = app.questionList[app.nowQuestionIdx]
              }else { // 修改完成回到列表
                layer.msg("保存题目成功");
                app.showQuestionList();
              }
            }
          }else {
            layer.msg(rst.errMsg);
          }
        }
      });
    });
  };
  app.showPaperList = function(rst){
    app.title.text(app.nowExamName + '-试卷列表');
    $("#paperList").show().siblings().hide();
    var _h = '';
    for(var i=0, l=app.paperListData.length; i<l; i++){
      var d = app.paperListData[i], p = '<a class="layui-btn publishPaper">发布</a>';
      _h += '<tr><td>'+d.subject+'</td><td>'+d.score+'</td>'+
            '<td data-id="'+d.id+'" data-url='+"'"+d.url+"'"+' data-statement="' + d.statement + '" data-subject="'+d.subject+'" data-score="'+d.score+'"><a class="layui-btn showQuestionList">查看</a><a class="layui-btn editPaper">修改</a>'+p+'</td></tr>';
    }
    $("#paperList table tbody").html(_h);

  };
  app.login = function(){
    var account = $.trim($("#account").val());
    var pwd = $.trim($("#password").val());
    if(account!="" && pwd!="" && account.length>1 && pwd.length>3){
      $.ajax({
        url: app.host + '/login', type: 'post', xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
        data: {"name": account, "password": pwd},
        success: function(rst){
          if(app.isLogin(rst)){
            layer.close(app.layIdx);
            app.examList();
          }else {
            layer.msg(rst.errMsg);
          }
        }
      });

    }else {
      layer.msg('请正确输入账号和密码');
    }
  };
  app.tool = ['undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch','forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist',  'cleardoc', '|',
            'fontfamily', 'fontsize', 'paragraph','|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'insertparagraphbeforetable','source' ];

});

try {

  app.initFn();

} catch (e) {
  console.log(e);
} finally {

}
